<?php
/**
 * 代表的是 swoole 里面后续所有的 task异步任务 都走这里
 * User: xiant_000
 * Date: 2018/11/25
 * Time: 10:06
 */

namespace app\common\lib\task;

use app\common\lib\ali\Sms;
use app\common\lib\redis\Predis;
use app\common\lib\Util;

class Task
{
    /**
     * 异步发送验证码
     *
     * @param $data
     * @param $serv swoole server 对象
     * @return mixed
     */
    public function sendSms($data, $serv)
    {
        $obj = new Sms();
        try {
            $response = $obj::sendSms($data['phone'], $data['code']);
        } catch (\Exception $e) {
            return Util::show('config.error', '阿里大于内部异常');
        }

        // 如果发送成功 验证码记录到 redis 里面grant all privileges on `*`.* to 'admin'@'%' identified by '123456';
        if ($response->Code === "OK") {
            Predis::getInstance()->set(Redis::smsKey($data['phone']), $data['code'], config('redis.out_time'));
            return Util::show(config('code.success'), 'success');
        } else {
            return Util::show(config('code.error'), '验证码发送失败');
        }
    }

    /**
     * 通过 task 机制形式，推送消息
     *
     * @param $data
     * @param $serv swoole server 对象
     */
    public function pushLive($data, $serv)
    {
//        $clients = Predis::getInstance()->sMembers(config('redis.live_game_key'));
        $clients = [
            3, 4, 5, 6, 7, 8, 9, 10
        ];
        foreach ($clients as $fd) {
            if ($serv->exist($fd)) {
                $serv->push($fd, json_encode($data));
            }
        }
    }
}
